package com.qdu.bussiness.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.qdu.bussiness.constant.BussinessConstant;
import com.qdu.bussiness.domain.BusBill;
import com.qdu.bussiness.service.IBusBillService;
import com.qdu.common.annotation.DataScope;
import com.qdu.common.core.domain.AjaxResult;
import com.qdu.common.utils.SecurityUtils;
import com.qdu.common.utils.StringUtils;
import com.qdu.common.utils.id.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qdu.bussiness.mapper.BusTicketPurchaseMapper;
import com.qdu.bussiness.domain.BusTicketPurchase;
import com.qdu.bussiness.service.IBusTicketPurchaseService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 购票记录Service业务层处理
 * 
 * @author qdu
 * @date 2022-03-06
 */
@Service
public class BusTicketPurchaseServiceImpl implements IBusTicketPurchaseService 
{
    @Autowired
    private BusTicketPurchaseMapper busTicketPurchaseMapper;

    @Autowired
    private IBusBillService busBillService;

    /**
     * 查询购票记录
     * 
     * @param purchaseId 购票记录主键
     * @return 购票记录
     */
    @Override
    public BusTicketPurchase selectBusTicketPurchaseByPurchaseId(Long purchaseId)
    {
        return busTicketPurchaseMapper.selectBusTicketPurchaseByPurchaseId(purchaseId);
    }

    /**
     * 查询购票记录列表
     * 
     * @param busTicketPurchase 购票记录
     * @return 购票记录
     */
    @Override
    public List<BusTicketPurchase> selectBusTicketPurchaseList(BusTicketPurchase busTicketPurchase)
    {
        if(!SecurityUtils.getUsername().equals("admin")){
            busTicketPurchase.setPurchaseUser(SecurityUtils.getUsername());
        }
        return busTicketPurchaseMapper.selectBusTicketPurchaseList(busTicketPurchase);
    }

    /**
     * 新增购票记录
     * 
     * @param busTicketPurchase 购票记录
     * @return 结果
     */
    @Override
    public AjaxResult insertBusTicketPurchase(BusTicketPurchase busTicketPurchase)
    {
        // 校验开始时间  当前时间应该小于等于开始时间
        if(busTicketPurchase.getTicketStartTime().compareTo(new Date()) < 0){
            return AjaxResult.error("当前时间已经超过了预约开始时间，请重新选择预约时段！");
        }

        // 查询当前是否存在预约门票
        String userName = SecurityUtils.getUsername();
        Date startTime = busTicketPurchase.getTicketStartTime();
        BusTicketPurchase nowTicketPurchase = busTicketPurchaseMapper.checkNowHasPurchaseTicket(userName, startTime);
        if(nowTicketPurchase != null) {
            // 根据状态判断，是预约了门票 没有使用 / 还是已经在使用了，无需重复预约
            String purchaseStatus = nowTicketPurchase.getPurchaseStatus();
            if (StringUtils.isEmpty(purchaseStatus))
                return AjaxResult.error("已存在预约门票包含当前时段，但门票状态未知！");
            if (BussinessConstant.PURCHASE_TICKET_STATUS_NOTUSED.equals(purchaseStatus))
                return AjaxResult.error("当前时段已存在未使用的预约门票，请直接入园检票！");
            // 预约购票记录
            if (BussinessConstant.PURCHASE_TICKET_STATUS_USING.equals(purchaseStatus))
                return AjaxResult.error("已存在预约门票包含当前时段，无需重复预约！");
        }
        // 生成门票预约记录
        busTicketPurchase.setPurchaseId(IdUtil.getId());
        busTicketPurchase.setPurchaseUser(SecurityUtils.getUsername());
        busTicketPurchase.setPurchaseTime(new Date());
        busTicketPurchase.setIsPaid(0L);
        busTicketPurchase.setPurchaseStatus(BussinessConstant.PURCHASE_TICKET_STATUS_NOTUSED);
        int res = busTicketPurchaseMapper.insertBusTicketPurchase(busTicketPurchase);
        return res > 0 ? AjaxResult.success() : AjaxResult.error("预约失败！");
    }

    /**
     * 修改购票记录
     * 
     * @param busTicketPurchase 购票记录
     * @return 结果
     */
    @Override
    public int updateBusTicketPurchase(BusTicketPurchase busTicketPurchase)
    {
        return busTicketPurchaseMapper.updateBusTicketPurchase(busTicketPurchase);
    }

    /**
     * 批量删除购票记录
     * 
     * @param purchaseIds 需要删除的购票记录主键
     * @return 结果
     */
    @Override
    public int deleteBusTicketPurchaseByPurchaseIds(Long[] purchaseIds)
    {
        return busTicketPurchaseMapper.deleteBusTicketPurchaseByPurchaseIds(purchaseIds);
    }

    /**
     * 删除购票记录信息
     * 
     * @param purchaseId 购票记录主键
     * @return 结果
     */
    @Override
    public int deleteBusTicketPurchaseByPurchaseId(Long purchaseId)
    {
        return busTicketPurchaseMapper.deleteBusTicketPurchaseByPurchaseId(purchaseId);
    }

    /**
     * 核销门票
     * @param purchaseId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult verifyTicketPurchase(Long purchaseId) {
        // 判断当前时间是否已经在 购票记录的开始时间以后
        BusTicketPurchase busTicketPurchase = busTicketPurchaseMapper.selectBusTicketPurchaseByPurchaseId(purchaseId);
        if(busTicketPurchase == null)
            return AjaxResult.error("尚未查询到门票记录，请刷新页面！");
        if(new Date().before(busTicketPurchase.getTicketStartTime()))
            return AjaxResult.error("当前门票还未到预约时间，无法核销！");
        if(new Date().after(busTicketPurchase.getTicketEndTime())){
            // 将门票状态 改成已超时
            BusTicketPurchase updateDto = new BusTicketPurchase();
            updateDto.setPurchaseId(purchaseId);
            updateDto.setPurchaseStatus(BussinessConstant.PURCHASE_TICKET_STATUS_OVERTIME);
            busTicketPurchaseMapper.updateBusTicketPurchase(updateDto);
            return AjaxResult.error("当前门票已超过预约时间，无法核销！");
        }
        // 判断当前用户是否为购买人
        if(!SecurityUtils.getUsername().equals("admin") &&
                !busTicketPurchase.getPurchaseUser().equals(SecurityUtils.getUsername()))
            return AjaxResult.error("当前门票非本人预约购买，无法核销！");
        // 查看状态是否已经 核销过
        if(!BussinessConstant.PURCHASE_TICKET_STATUS_NOTUSED.equals(busTicketPurchase.getPurchaseStatus())){
            return AjaxResult.error("当前门票已核销！无法重复核销！");
        }
        // 核销 ： 1。修改购票记录状态 2.生成账单，并关联

        // 生成账单
        BusBill newBill = new BusBill();
        Long billId = IdUtil.getId();
        newBill.setBillId(billId);
        newBill.setBillIsPaid(0L);
        newBill.setBillStatus("正常");
        int billRes = busBillService.insertBusBill(newBill);
        if(billRes < 1){
            return AjaxResult.error("账单生成失败！核销失败！");
        }
        // 修改购票记录 状态和关联订单
        BusTicketPurchase updateDto = new BusTicketPurchase();
        updateDto.setPurchaseId(purchaseId);
        updateDto.setPurchaseStatus(BussinessConstant.PURCHASE_TICKET_STATUS_USING);
        updateDto.setBillId(billId);
        updateDto.setTicketVerifyTime(new Date());
        int purchaseRes = busTicketPurchaseMapper.updateBusTicketPurchase(updateDto);
        if(purchaseRes < 1){
            throw new RuntimeException("核销失败！");
        }

        return AjaxResult.success();
    }

    /**
     * 获取当前用户今天的门票情况
     * @return
     */
    public BusTicketPurchase getTodayTicketPurchase(){
        String username = SecurityUtils.getUsername();
        SimpleDateFormat startTimeFormat = new SimpleDateFormat("YYYY-MM-dd 00:00:00");
        String startTime = startTimeFormat.format(new Date());
        SimpleDateFormat endTimeFormat = new SimpleDateFormat("YYYY-MM-dd 23:59:59");
        String endTime = endTimeFormat.format(new Date());
        return busTicketPurchaseMapper.getTodayVerifyTicket(username, startTime, endTime);
    }

    /**
     * 获取所有人今天的门票情况
     * @return
     */
    @Override
    public List<BusTicketPurchase> getTodayAllTicketPurchase() {
        SimpleDateFormat startTimeFormat = new SimpleDateFormat("YYYY-MM-dd 00:00:00");
        String startTime = startTimeFormat.format(new Date());
        SimpleDateFormat endTimeFormat = new SimpleDateFormat("YYYY-MM-dd 23:59:59");
        String endTime = endTimeFormat.format(new Date());
        return busTicketPurchaseMapper.getTodayAllVerifyTicket(startTime, endTime);
    }
}
